package com.jcl.core.security;

import com.jcl.core.security.entity.ResultEnum;
import com.jcl.core.security.entity.UserDetail;
import com.jcl.core.security.utils.JwtTokenUtil;
import com.jcl.core.security.utils.ResultUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName AjaxAuthenticationSuccessHandler
 * @Author yyliu
 * @Date 2018/12/18 11:25
 * @Version 1.0
 **/
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        UserDetail userDetail = (UserDetail) authentication.getPrincipal();

        String jwtToken = JwtTokenUtil.generateToken(userDetail.getUsername(), JwtTokenUtil.EXPIRATION);

        ResultUtil.success(response,
                ResultEnum.USER_LOGIN_SUCCESS.getMessage(), ResultEnum.USER_LOGIN_SUCCESS.getCode(),
                jwtToken);

    }
}
